import { createNotices, searchNotices, deleteNotices, getUserNotices } from '@/services/notices.js'
import { binMsg } from '@/global/api.js'

const noticesModule = {
  namespaced: true,
  state() {
    return {
      // 管理员的公告历史
      noticesList: [],
      noticesCount: 0,
      // 用户的查看公告
      myNoticesList: [],
      myNoticesCount: 0
    }
  },

  mutations: {
    changeNoticesList(state, list) {
      state.noticesList = list
    },
    changeNoticesCount(state, count) {
      state.noticesCount = count
    },
    changeMyNoticesList(state, list) {
      state.myNoticesList = list
    },
    changeMyNoticesCount(state, count) {
      state.myNoticesCount = count
    },
    clearState(state) {
      state.noticesList = []
      state.myNoticesList = []
    }
  },

  actions: {
    // 查询公告列表数据
    async searchAction({ commit }, payload) {
      const { data: res } = await searchNotices(payload)
      if (res.meta.status !== 200) return
      commit('changeNoticesList', res.data.list)
      commit('changeNoticesCount', res.data.total)
    },

    // 发布公告（创建）
    async createAction({ commit }, payload) {
      console.log(payload)
      const { data: res } = await createNotices(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
    },

    // 删除公告
    async deleteAction({ commit,state }, payload) {
      const { data: res } = await deleteNotices(payload.id)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      const newList = state.noticesList.filter((item) => item._id !== payload.id)
      const newCount = state.noticesCount - 1
      commit('changeNoticesList', newList)
      commit('changeNoticesCount', newCount)
      binMsg('success', res.meta.msg)
    },

    // 获取当前用户可查看的公告
    async getMyNoticesAction({ commit }, payload) {
      const { data: res } = await getUserNotices(payload)
      if (res.meta.status !== 200) return
      commit('changeMyNoticesList', res.data.list)
      commit('changeMyNoticesCount', res.data.total)
    }
  },

  getters: {
    // 根据id获取历史某条公告
    getHistoryNoticeById(state) {
      return (id) => {
        let notice = null
        state.noticesList.some(item => {
          if (item._id === id) {
            notice = item
            return true
          }
        })
        return notice
      }
    },
    // 根据id获取用户某条公告
    getMyNoticeById(state) {
      return (id) => {
        let notice = null
        state.myNoticesList.some(item => {
          if (item._id === id) {
            notice = item
            return true
          }
        })
        return notice
      }
    }
  }
}

export default noticesModule
